import cv2
from PyQt5.QtGui import QImage, QPixmap
from PyQt5.QtCore import Qt

def start_camera(window):
    if not window.cap:
        window.cap = cv2.VideoCapture(0)
        if not window.cap.isOpened():
            window.statusBar.showMessage("无法打开摄像头", 5000)
            return
        
        # 设置摄像头分辨率为 1920x1080 或其他高分辨率
        window.cap.set(cv2.CAP_PROP_FRAME_WIDTH, 1920)
        window.cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 1080)

        window.timer.start(30)  # 每30毫秒更新一次帧
        window.statusBar.showMessage("摄像头已打开")

def stop_camera(window):
    if window.cap:
        window.timer.stop()
        window.cap.release()
        window.cap = None
        window.statusBar.showMessage("摄像头已关闭")

def update_frame(window):
    ret, frame = window.cap.read()
    if ret:
        # 转换为灰度图像
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

        # 进行人脸检测
        faces = window.face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30))

        # 在检测到的人脸上绘制矩形框
        for (x, y, w, h) in faces:
            cv2.rectangle(frame, (x, y), (x+w, y+h), (255, 0, 0), 2)

        # 转换颜色格式
        frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
        h, w, ch = frame.shape
        bytes_per_line = ch * w
        qt_image = QImage(frame.data, w, h, bytes_per_line, QImage.Format_RGB888)
        pixmap = QPixmap.fromImage(qt_image)
        window.label.setPixmap(pixmap.scaled(window.label.width(), window.label.height(), Qt.KeepAspectRatio, Qt.SmoothTransformation))